#include "Geometry.h"

HRESULT Geometry::Render()
{
	//set vertex buffer
	static const UINT stride = (UINT)m_vertSize;
	static const UINT offset = 0;
	m_imContext->IASetVertexBuffers(0, 1, &m_pvBuf, &stride, &offset);
	//set index buffer
	m_imContext->IASetIndexBuffer(m_piBuf, DXGI_FORMAT_R32_UINT, 0);
	//render
	m_imContext->DrawIndexed((UINT)m_nIndices, 0, 0);
	return S_OK;
}

HRESULT Geometry::Init(ID3D11Device* device, ID3D11DeviceContext* imContext)
{
	m_device = device;
	m_imContext = imContext;

	HRESULT hr;
	//create buffer
	D3D11_BUFFER_DESC bd;
	D3D11_SUBRESOURCE_DATA initData;
	ZeroMemory(&bd, sizeof(bd));
	ZeroMemory(&initData, sizeof(initData));

	//create verte buffer
	bd.Usage = D3D11_USAGE_DEFAULT;
	bd.ByteWidth = (UINT)(m_vertSize*m_nVerts);
	bd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
	initData.pSysMem = m_pVerts;
	hr = device->CreateBuffer(&bd, &initData, &m_pvBuf);
	assert(SUCCEEDED(hr));

	ZeroMemory(&bd, sizeof(bd));
	ZeroMemory(&initData, sizeof(initData));

	//create index buffer
	bd.Usage = D3D11_USAGE_DEFAULT;
	bd.ByteWidth = (UINT)(sizeof(UINT)*m_nIndices);
	bd.BindFlags = D3D11_BIND_INDEX_BUFFER;
	initData.pSysMem = m_pIndices;
	hr = device->CreateBuffer(&bd, &initData, &m_piBuf);
	assert(SUCCEEDED(hr));

	return hr;
}

HRESULT Geometry::Load(void* pVert, size_t vertSize, size_t nVerts, UINT* pIndices, size_t nIndices)
{
	m_pVerts = pVert;
	m_vertSize = vertSize;
	m_pIndices = pIndices;
	m_nVerts = nVerts;
	m_nIndices = nIndices;
	return S_OK;
}

Geometry::~Geometry()
{
	if(m_pvBuf) m_pvBuf->Release();
	if(m_piBuf) m_piBuf->Release();
	if(m_pIndices) delete [] m_pIndices;
	if(m_pVerts) delete [] m_pVerts;
}

Geometry::Geometry()
{
	ZeroMemory(this, sizeof(this));
	m_world = XMMatrixIdentity();
}
